# encoding=utf-8
import random
import uuid

from guangxi.utils.area_helper import AreaHelper
from zc_core.middlewares.agents.user_agents import agents
from zc_core.util.encrypt_util import md5


class ZcySupplierMiddleware(object):
    """
    商品列表页/供应商列表页
    专用反爬中间件
    """
    def __init__(self):
        self.referer = 'https://www.zcygov.cn/pages/suppliers?utm=a0eer.2ef5w01f.cl22.1.{}&pageNo={}&pageSize=10'
        self.area_helper = AreaHelper()
        # proxy -> log_client_uuid
        self.log_client_map = dict()
        # proxy -> area_id
        self.area_map = dict()

    def process_request(self, request, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        page = meta.get('page', 1)
        req_type = meta.get('reqType', None)
        if req_type in ['supplier']:
            request.headers['User-Agent'] = random.choice(agents)
            log_client = self.log_client_map.get(proxy)
            if not log_client:
                log_client = str(uuid.uuid4())
                self.log_client_map[proxy] = log_client
            area_id = self.area_map.get(proxy)
            if not area_id:
                area_id = self.area_helper.random_choice()
                self.area_map[proxy] = area_id
            request.headers['Cookie'] = '_zcy_log_client_uuid={}; aid={}; districtCode=459900'.format(log_client, area_id)
            request.headers['Referer'] = random.choice(self.referer).format(md5(str(uuid.uuid4())), page)

    def process_response(self, request, response, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        page = meta.get('page', 1)
        req_type = meta.get('reqType', None)
        if req_type in ['supplier'] and response.status == 405:
            # 只观察，不处理
            spider.logger.info('触发反爬: proxy=%s, page=%s' % (proxy, page))
            self.log_client_map.pop(proxy, None)

        return response

    def process_exception(self, request, exception, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        page = meta.get('page', 1)
        req_type = meta.get('reqType', None)
        if req_type in ['sku', 'supplier']:
            # 只观察，不处理
            spider.logger.info('反爬异常: proxy=%s, page=%s, ex=%s' % (proxy, page, str(type(exception))))


class ZcySkuMiddleware(object):
    """
    商品列表页/供应商列表页
    专用反爬中间件
    """
    def __init__(self):
        self.referer_tpl = [
            'https://www.zcygov.cn/',
            'https://www.zcygov.cn/eevees/shop?shopId={}&searchType=1&utm=a0017.2ef5001f.cl47.2.{}',
        ]
        self.area_helper = AreaHelper()
        # proxy -> log_client_uuid
        self.log_client_map = dict()
        # proxy -> area_id
        self.area_map = dict()

    def process_request(self, request, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        req_type = meta.get('reqType', None)
        if req_type in ['sku', 'supplier']:
            request.headers['User-Agent'] = random.choice(agents)
            log_client = self.log_client_map.get(proxy)
            if not log_client:
                log_client = str(uuid.uuid4())
                self.log_client_map[proxy] = log_client
            area_id = self.area_map.get(proxy)
            if not area_id:
                area_id = self.area_helper.random_choice()
                self.area_map[proxy] = area_id
            request.headers['Cookie'] = '_zcy_log_client_uuid={}; aid={}; districtCode=459900'.format(log_client, area_id)
        if req_type in ['sku']:
            sp_id = meta.get('supplierId')
            request.headers['Referer'] = random.choice(self.referer_tpl).format(sp_id, md5(str(uuid.uuid4())))

    def process_response(self, request, response, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        req_type = meta.get('reqType', None)
        if req_type in ['sku'] and response.status == 405:
            # 只观察，不处理
            spider.logger.info('触发反爬: proxy=%s' % proxy)
            self.log_client_map.pop(proxy, None)

        return response

    def process_exception(self, request, exception, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        req_type = meta.get('reqType', None)
        if req_type in ['sku', 'supplier']:
            # 只观察，不处理
            spider.logger.info('反爬异常: proxy=%s, ex=%s' % (proxy, str(type(exception))))


class ZcyItemMiddleware(object):
    """
    商品详情页
    专用反爬中间件
    """
    def __init__(self):
        self.referer_tpl = [
            'https://www.zcygov.cn/items/{}?searchType=1',
            'https://www.zcygov.cn/items/{}?utm=a0017.2ef5001f.cl47.32.{}',
            'https://www.zcygov.cn/items/{}?searchType=1&utm=a0004.eevees-search.c0002.d0003.{}',
        ]
        self.area_helper = AreaHelper()
        # proxy -> log_client_uuid
        self.log_client_map = dict()
        # proxy -> area_id
        self.area_map = dict()

    def process_request(self, request, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        sku_id = meta.get('skuId', '')
        req_type = meta.get('reqType', None)
        if sku_id and 'item' == req_type:
            request.headers['User-Agent'] = random.choice(agents)
            request.headers['Referer'] = random.choice(self.referer_tpl).format(sku_id, md5(str(uuid.uuid4())))
            log_client = self.log_client_map.get(proxy)
            if not log_client:
                log_client = str(uuid.uuid4())
                self.log_client_map[proxy] = log_client
            area_id = self.area_map.get(proxy)
            if not area_id:
                area_id = self.area_helper.random_choice()
                self.area_map[proxy] = area_id
            request.headers['Cookie'] = '_zcy_log_client_uuid={}; aid={}; districtCode=459900'.format(log_client, area_id)

    def process_response(self, request, response, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        sku_id = meta.get('skuId', '')
        req_type = meta.get('reqType', None)
        if sku_id and 'item' == req_type and response.status == 405:
            # 只观察，不处理
            spider.logger.info('触发反爬: proxy=%s, sku=%s' % (proxy, sku_id))
            self.log_client_map.pop(proxy, None)

        return response

    def process_exception(self, request, exception, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        sku_id = meta.get('skuId', '')
        req_type = meta.get('reqType', None)
        if sku_id and 'item' == req_type:
            # 只观察，不处理
            spider.logger.info('反爬异常: proxy=%s, sku=%s, ex=%s' % (proxy, sku_id, str(type(exception))))


# class ZcyOrderMiddleware(object):
#     """
#     订单明细
#     专用反爬中间件
#     """
#     def __init__(self):
#         self.referer_tpl = [
#             'https://www.zcygov.cn/items/{}?searchType=1',
#             'https://www.zcygov.cn/items/{}?utm=32123.rw350d12.t544.33.{}',
#             'https://www.zcygov.cn/items/{}?searchType=1&utm=32123.eevees-search.e2002.c3103.{}',
#         ]
#         self.area_helper = AreaHelper()
#         # proxy -> log_client_uuid
#         self.log_client_map = dict()
#         # proxy -> area_id
#         self.area_map = dict()
#
#     def process_request(self, request, spider):
#         meta = request.meta
#         proxy = meta.get('proxy', 'NO_PROXY')
#         sku_id = meta.get('skuId', '')
#         req_type = meta.get('reqType', None)
#         if sku_id and 'order' == req_type:
#             request.headers['User-Agent'] = random.choice(agents)
#             request.headers['Referer'] = random.choice(self.referer_tpl).format(sku_id, md5(str(uuid.uuid4())))
#             log_client = self.log_client_map.get(proxy)
#             if not log_client:
#                 log_client = str(uuid.uuid4())
#                 self.log_client_map[proxy] = log_client
#             area_id = self.area_map.get(proxy)
#             if not area_id:
#                 area_id = self.area_helper.random_choice()
#                 self.area_map[proxy] = area_id
#             request.headers['Cookie'] = '_zcy_log_client_uuid={}; acw_tc={}; aid={}; districtCode=459900; districtName=%E9%87%8D%E5%BA%86%E5%B8%82%E6%9C%AC%E7%BA%A7'.format(log_client, md5(log_client)+md5(area_id), area_id)
#
#     def process_response(self, request, response, spider):
#         meta = request.meta
#         proxy = meta.get('proxy', 'NO_PROXY')
#         sku_id = meta.get('skuId', '')
#         req_type = meta.get('reqType', None)
#         if sku_id and 'order' == req_type and response.status == 405:
#             # 只观察，不处理
#             spider.logger.info('触发反爬: proxy=%s, sku=%s' % (proxy, sku_id))
#             self.log_client_map.pop(proxy, None)
#
#         return response
#
#     def process_exception(self, request, exception, spider):
#         meta = request.meta
#         proxy = meta.get('proxy', 'NO_PROXY')
#         sku_id = meta.get('skuId', '')
#         req_type = meta.get('reqType', None)
#         if sku_id and 'order' == req_type:
#             # 只观察，不处理
#             spider.logger.info('反爬异常: proxy=%s, sku=%s, ex=%s' % (proxy, sku_id, str(type(exception))))


class ZcyOrderMiddleware(object):
    """
    订单明细
    专用反爬中间件
    """
    def __init__(self):
        self.referer_tpl = [
            'https://www.zcygov.cn/items/{}?searchType=1',
            'https://www.zcygov.cn/items/{}?utm=c23317.e235002a.r327.21.{}',
            'https://www.zcygov.cn/items/{}?searchType=1&utm=a0004.eevees-search.g400s.d2033.{}',
        ]
        self.area_helper = AreaHelper()
        # proxy -> log_client_uuid
        self.log_client_map = dict()
        # proxy -> area_id
        self.area_map = dict()

    def process_request(self, request, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        sku_id = meta.get('skuId', '')
        req_type = meta.get('reqType', None)
        if sku_id and 'order' == req_type:
            request.headers['User-Agent'] = random.choice(agents)
            request.headers['Referer'] = random.choice(self.referer_tpl).format(sku_id, md5(str(uuid.uuid4())))
            log_client = self.log_client_map.get(proxy)
            if not log_client:
                log_client = str(uuid.uuid4())
                self.log_client_map[proxy] = log_client
            area_id = self.area_map.get(proxy)
            if not area_id:
                area_id = self.area_helper.random_choice()
                self.area_map[proxy] = area_id
            request.headers['Cookie'] = '_zcy_log_client_uuid={}; aid={}; districtCode=001001'.format(log_client, area_id)

    def process_response(self, request, response, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        sku_id = meta.get('skuId', '')
        req_type = meta.get('reqType', None)
        if sku_id and 'order' == req_type and response.status == 405:
            # 只观察，不处理
            spider.logger.info('触发反爬: proxy=%s, sku=%s' % (proxy, sku_id))
            self.log_client_map.pop(proxy, None)

        return response

    def process_exception(self, request, exception, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        sku_id = meta.get('skuId', '')
        req_type = meta.get('reqType', None)
        if sku_id and 'order' == req_type:
            # 只观察，不处理
            spider.logger.info('反爬异常: proxy=%s, sku=%s, ex=%s' % (proxy, sku_id, str(type(exception))))